package cz.tomasdvorak.cars.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Methods for MD5 and SHA1 hash counting.
 */
public final class Hashing {
    private Hashing() {} // no instance

    public static String md5(String string) {
        return hash(string, "MD5");
    }

    public static String sha1(String string) {
        return hash(string, "SHA-1");
    }

    private static String hash(String string, String method) {
        try {
            MessageDigest md = MessageDigest.getInstance(method);
            byte[] digest = md.digest(string.getBytes());
            return convertToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String convertToHex(byte[] digest) {
        StringBuilder hexValue = new StringBuilder();
        for (byte digestByte : digest) {
            int val = ((int) digestByte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }
}
